<template>
  <div>
    <el-container>
      <el-aside width="280px">
        <div class="plr-4">
          <div class="app_card mb-2 pt-4  pb-4" style="height:calc(100vh - 200px);overflow-y: scroll;">
            <!--            @node-click="onClickNode"-->
            <el-tree :data="dataOfGroups" :load="loadNode" lazy icon="CaretBottom" node-key="id" :props="{
              label: 'name',
              children: 'children', isLeaf: 'isLeaf'
            }" @nodeClick="onClickNode">
              <template #default="{ node, data }">
                <span :class="{ 'is-active': data.id === selectedRoom.id && data.level === 2 }">{{ node.label }}</span>
              </template>
            </el-tree>
          </div>
        </div>
      </el-aside>
      <el-main v-if="selectedRoom.id">
        <div class="app_card mb-2 pt-4 pb-4 search-form">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <el-radio-group class="radio_button" v-model="filterFloor" @change="onRefresh">
                <el-radio-button :label="1">全部课程</el-radio-button>
                <el-radio-button :label="2">直播课程</el-radio-button>
                <el-radio-button :label="3">点播课程</el-radio-button>
              </el-radio-group>

            </div>
            <div>
              <el-select v-model="semesterValue" value-key="id" style="width:200px" placeholder="请选择" class="mr-3"
                @change="onChangeSemester">
                <el-option v-for="item of semesterOptions" :key="item.id" :label="item.semesterName" :value="item" />
              </el-select>
              <el-select v-model="queryParam.week" style="width:100px" placeholder="请选择" class="mr-3" @change="onRefresh">
                <el-option v-for="item in weekOptions" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
              <el-button type="primary" @click="onVod()">自定义录播排程</el-button>
              <el-button type="primary" @click="onLive()">自定义直播排程</el-button>

            </div>
          </div>
        </div>
        <div class="app_card pt-4  pb-5">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-22">
                {{ selectedRoom?.Building.Campus.Name }}
                {{ selectedRoom?.Building.name }}
                {{ selectedRoom.name }}
              </div>
              <div class="text-16 text-white-50 mt-3" v-if="semesterValue?.startTime">
                排课教室：{{ selectedRoom.name }}
                排课日期：{{ baseDate().startOf('isoWeek').format("YYYY-MM-DD") }} 至 {{
                  baseDate().endOf('isoWeek').format("YYYY-MM-DD") }}
              </div>
            </div>
            <div class="">
              <el-button type="primary" @click="showMultiRowClick()">多节编辑</el-button>
            </div>
          </div>
          <div style="height:calc(100vh - 380px);overflow-y: scroll;margin-top:40px">
            <div class="border-start  border-bottom  border-end clearfix rounded-4 text-truncate">
              <div class="position-relative clearfix bg-row">
                <div class="position-relative float-start  solid-top   t-c section-width">
                </div>
                <div class="position-relative float-start solid-left solid-top t-l week-width" v-for="k in 7">
                  <div class="text-14" v-if="semesterValue?.startTime">
                    {{ baseDate().startOf('isoWeek').add(k - 1, 'd').format("dddd") }}</div>
                  <div class="text-12 pt-2" v-if="semesterValue?.startTime">{{
                    baseDate().startOf('isoWeek').add(k - 1, 'd').format("MM月DD日") }}</div>
                </div>
              </div>
              <div class=" position-relative clearfix" v-for="item of lessonOptions">
                <div class="position-relative float-start  solid-top   t-c section-width bg-row">
                  <div class="fw-medium text-14">第{{ item.id }}节</div>
                </div>
                <div class="position-relative float-start solid-left solid-top   t-l week-width"
                  v-for="(weekItem, weekIdx) of loadDataFormat(item.id, dataOfTable)"
                  @click="handleRowClick(weekIdx, item.id - 1)">
                  <div v-if="weekItem.record?.id || weekItem.live?.id">
                    <Delete style="width: 1rem;" class="scheduling-selected" color="#ff0000" :size="12"
                      @click.stop="onDeleteTask(weekItem.record, weekItem.live)"></Delete>
                    <div class="text-16 fw-bolder">{{ weekItem.record?.Teacher.name || weekItem.live?.Teacher.name }}</div>
                    <!--                    <div class="text-12 pt-2">{{weekItem.record?.startTime}}-{{weekItem.record?.endTime}}</div>-->
                    <div class="text-12 pt-2">
                      <template v-if="weekItem.record?.id">点播</template>
                      <template v-if="weekItem.record?.id && weekItem.live?.id"> | </template>
                      <template v-if="weekItem.live?.id">{{ weekItem.live?.liveTaskRole ? '互动直播' : '普通直播' }}</template>
                    </div>
                  </div>
                  <template v-else>
                    <div class="text-12 text-bs fw-medium t-c pt-3 position-relative">
                      <el-checkbox class="scheduling-selected" :checked="lessonSelected[item.id] && weekIdx === weekValue"
                        @change="handleMultiRowClick(weekIdx, item.id, $event)" @click.stop=""></el-checkbox>
                      <el-icon>
                        <Plus />
                      </el-icon>新增
                    </div>
                  </template>
                </div>
              </div>
              <div class=" position-relative clearfix" v-for="(key) in customColIdx">
                <div class="position-relative float-start solid-top   t-c section-width bg-row">
                  <div class="fw-medium text-14">自定义排程</div>
                </div>
                <div class="position-relative float-start solid-left solid-top   t-l week-width" v-for="i in 7">
                  <template v-if="customDataOfTable[i - 1][key - 1]?.id">
                    <Delete style="width: 1rem;" class="scheduling-selected" color="#ff0000" :size="12"
                      @click.stop="onDeleteCustomTask(customDataOfTable[i - 1][key - 1])"></Delete>
                    <div class="text-16 fw-bolder">{{ customDataOfTable[i - 1][key - 1]?.Teacher.name }}</div>
                    <div class="text-12 pt-2">
                      <template v-if="customDataOfTable[i - 1][key - 1]?.isLive">{{ customDataOfTable[i - 1][key
                        - 1]?.liveTaskRole ? '互动直播' : '普通直播' }}</template>
                      <template v-else>点播</template>
                    </div>
                    <div class="text-12 pt-1">{{ customDataOfTable[i - 1][key
                      - 1]?.startTime.slice(0, 5) }}-{{ customDataOfTable[i - 1][key - 1]?.endTime.slice(0, 5) }}</div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
      <EditDialog ref="editDialogRef" @success="loadData()"></EditDialog>
      <VodDialog ref="vodDialogRef" @success="loadData()"></VodDialog>
      <LiveDialog ref="liveDialogRef" @success="loadData()"></LiveDialog>
    </el-container>
  </div>
</template>

<script setup>
/**
 * 教室管理
 */
import { ref, onMounted} from 'vue';
import { ElMessageBox, ElMessage, dayjs } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import useAuthStore from '@/stores/useAuthStore';

//组件
import VodDialog from './VodDialog.vue';
import LiveDialog from './LiveDialog.vue';
import EditDialog from './EditDialog.vue';
import moment from "moment";
moment.locale('zh-cn', {
  weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
});
// ======================================================
//                      变量声明
// ======================================================




const authStore = useAuthStore();
const filterFloor = ref(1);
// 组件引用
const editDialogRef = ref(null);
const liveDialogRef = ref(null);
const vodDialogRef = ref(null);
const selectedRoom = ref({})
// 表格数据 不知道数据格式是什么暂时用以下格式
const weekCourse = ref([]);
// 表格数据
const dataOfGroups = ref([]);
const dataOfTable = ref([]);
const customColIdx = ref(0)
const customDataOfTable = ref([])
const semesterValue = ref({})
const lessonSelected = ref({})
const semesterOptions = ref([])
const lessonOptions = ref([])
const weekValue = ref(null)

const weekOptions = ref([])


// 表格查询参数
const queryParam = ref({
  semesterId: null,
  week: null,
  roomId: null,
  // page: 1,
  // pageSize: 10,
})


const baseDate = () => {
  return moment(semesterValue.value.startTime).add(queryParam.value.week - 1, 'week')
}
// ======================================================
//                      点击操作
// ======================================================
const onChangeSemester = async (e) => {
  queryParam.value.semesterId = e.id
  await formatWeek()
  await loadData()
}


// ======================================================
//                      树形处理事件
// ======================================================
const floorChange = () => {
  if (radioFloor.value == "-2") {
  } else if (radioFloor.value == "-3") {
  } else if (radioFloor.value == "-1") {
  } else {
  }
  onRefresh()
}
const loadNode = (node, resolve) => {
  setTimeout(function() {  
    if (node.data.level === 0) {
     EsAjax.post(ApiUrls.buildingList, { campusId: node.data.id }).then((res) => {
      console.log(res.data.data.list)
      resolve(res.data.data.list.map(item => ({ id: item.id, name: item.name, level: 1, campusId: node.data.id })))
    })
    return
  }
  if (node.data.level === 1) {
     EsAjax.post(ApiUrls.roomList, { campusId: node.data.campusId, buildingId: node.data.id }).then((res) => {
      console.log(res.data.data.list)
      resolve(res.data.data.list.map(item => {
        item.name = item.Name
        item.level = 2
        item.isLeaf = true
        return item
      }))
    })
    return
  }
  resolve([])
}, 500);
  
}
// 点击分组树形节点
const onClickNode = async (data) => {
  console.log('点击树形节点', data)
  console.log(data)
  if (data.level === 2) {
    queryParam.value.roomId = data.id;
    selectedRoom.value = data
    queryParam.value.page = 1
    await getSemesterList()

  }
}


const loadTreeData = () => {
  EsAjax.post(ApiUrls.campusList).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    dataOfGroups.value = res.data.data.list.map(item => ({ id: item.id, name: item.Name, level: 0 }));
  }).catch(err => {
    ElMessage.error(err.message);
  })
}


// 点击刷新按钮
const onRefresh = () => {
  queryParam.value.page = 1;
  loadData();
}

// 点击新增按钮
const onEditRow = (row = null) => {
  editDialogRef.value.show(row.id || 0, "课表设置", row);
}
// 点击新增按钮
const onLive = (row = {}) => {
  row._room = selectedRoom.value//当前 周的节次
  row._semester = semesterValue.value //当前 学期
  row._week = queryParam.value.week//当前 周
  liveDialogRef.value.show(0, "自定义直播排程", row);
}
// 点击新增按钮
const onVod = (row = {}) => {
  row._room = selectedRoom.value//当前 周的节次
  row._semester = semesterValue.value //当前 学期
  row._week = queryParam.value.week//当前 周
  vodDialogRef.value.show(0, "自定义录播排程", row);
}





const arraySpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {

  if (rowIndex === 2) {
    if (columnIndex === 0) {
      return [1, 8]
    } else if (columnIndex === 1) {
      return [0, 0]
    }
  }
}



const getDialogInfo = (i, lessons) => {
  const current = {}
  current._semester = semesterValue.value //当前 学期
  current._week = queryParam.value.week//当前 周
  current._lessons = lessons//当前 周的节次
  current._room = selectedRoom.value//当前 周的节次
  current._course = {} //当前 课程
  current._index = i//当前 选择
  console.log(current)
  return current
}

// 当某一行被点击时会触发该事件
const handleRowClick = (i, lessonIdx) => {
  // weekCourse.value[i].isChick = !weekCourse.value[i].isChick
  // if (weekCourse.value[i].isChick) {

  onEditRow(getDialogInfo(i, [lessonOptions.value[lessonIdx]]))
  // }
  // liveDialogRef.value.show(row.id, "课表编辑设置", [row]);
}
const handleMultiRowClick = (i, lessonId, bool) => {
  weekValue.value = i
  if (bool) {
    lessonSelected.value[lessonId] = lessonOptions.value[lessonId - 1]
  } else {
    delete lessonSelected.value[lessonId]
  }
}
const showMultiRowClick = () => {
  const lessons = Object.values(lessonSelected.value)
  if (lessons.length) {
    onEditRow(getDialogInfo(weekValue.value, lessons))
  } else {
    ElMessage.info("请选择批量数据");
  }
}
const onDeleteTask = (record = {}, live = {}) => {
  ElMessageBox.confirm("确认删除排程？", "提示", {
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        console.log(ApiUrls.recordTaskDelete)
        if (live.id) {
          await EsAjax.delete(ApiUrls.liveTaskDelete, { data: { id: (live.id || "").toString() } })
            .then(res => {
              if (res.data.code !== 200) {
                ElMessage.warning(res.data.msg);
                return;
              }
            })
            .catch(err => {
              ElMessage.error("网络错误：", err.message)
            })
        }
        if ((record.id || "")) {
          await EsAjax.delete(ApiUrls.recordTaskDelete, { data: { id: (record.id || "").toString() } }).then((_res) => {
            if (_res.data.code !== 200) {
              ElMessage.warning(res.data.msg);
              return;
            }
          }).catch(err => {
            ElMessage.error("网络错误：", err.message)
          })
        }
        ElMessage.success("操作成功");
        loadData();
        instance.confirmButtonLoading = false;
        done();
      } else {
        done()
      }
    }
  })
}
const onDeleteCustomTask = (event) => {
  if (event) {
    let live = { id: "" }
    if (event.isLive) {
      onDeleteTask({}, { id: event.id })
    } else {
      onDeleteTask({ id: event.id }, {})
    }
  }
}
// ======================================================
//                      表格处理事件
// ======================================================
const loadDataFormat = (lessonIdx, data) => {
  const weeks = [{}, {}, {}, {}, {}, {}, {}]
  const _data = JSON.parse(JSON.stringify(data))
  weeks.forEach((item, weekIdx) => {
    _data.forEach((_item, idx) => {
      if (_item.classDay === baseDate().startOf('isoWeek').add(weekIdx, 'd').format('YYYY-MM-DD')) {
        _item.classId.split(',').forEach(__item => {
          if (lessonIdx.toString() === __item) {
            console.log(_item)
            if (_item.isLive) {
              weeks[weekIdx].live = _item
            } else {
              weeks[weekIdx].record = _item
            }
          }
        })
      }
    })
  })
  return weeks
}
const loadCustomDataFormat = (data) => {
  const weeks = {}
  customColIdx.value = 0
  customDataOfTable.value = []
  for (let i = 0; i < 7; i++) {
    weeks[baseDate().startOf('isoWeek').add(i, 'd').format('YYYYMMDD')] = []
  }
  const _data = JSON.parse(JSON.stringify(data))
  _data.forEach((_item) => {
    if (!_item.classId) {
      const day = _item.classDay.replaceAll('-', '')
      weeks[day].push(_item)
      if (customColIdx.value < weeks[day].length) {
        customColIdx.value = weeks[day].length
      }
    }
  })
  customDataOfTable.value = Object.values(weeks)
}
const loadData = () => {
  dataOfTable.value = []
  console.log(dataOfTable.value)
  EsAjax.post(ApiUrls.liveTaskGetAll, queryParam.value).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    EsAjax.post(ApiUrls.recordTaskGetAll, queryParam.value).then(_res => {
      if (_res.data.code !== 200) {
        ElMessage.warning(_res.data.msg);
        return;
      }
      let lives = []
      let records = []
      if (filterFloor.value === 1 || filterFloor.value === 2) {
        lives = res.data.data.list.map(item => { item.isLive = true; return item; })
      }
      if (filterFloor.value === 1 || filterFloor.value === 3) {
        records = _res.data.data.list
      }
      const list = [].concat(lives, records)
      dataOfTable.value = list;
      loadCustomDataFormat(list)
    }).catch(err => {
      ElMessage.error(err.message);
    })
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const loadRecordData = () => {

}
const loadLiveData = () => {

}

const formatWeek = () => {
  weekOptions.value = []
  queryParam.value.semesterId = semesterValue.value.id
  queryParam.value.week = semesterValue.value.nowWeek
  for (let i = 0; i < semesterValue.value.totalWeek; i++) {
    weekOptions.value.push({ value: i + 1, name: `第${i + 1}周` })
  }
}

const getSemesterList = () => {
  EsAjax.post(ApiUrls.semesterList, { nowTime: dayjs().format('YYYY-MM-DD') }).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    semesterOptions.value = res.data.data.list;
    semesterValue.value = semesterOptions.value[0]
    formatWeek()
    loadData();
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const getLessonList = () => {
  EsAjax.post(ApiUrls.lessonList, {}).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    lessonOptions.value = res.data.data.list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

onMounted(async () => {
  await loadTreeData();
  await getLessonList();
  // getSemesterList()
  // loadData();
})

</script>
<style lang="less" scoped>
.class_name {
  position: absolute;
  font-size: 20px;
  left: 30px;
  top: 10px;
  font-weight: bold;
}

.section-width {
  width: 9%;
  height: 80px;
  line-height: 80px;
  box-sizing: border-box;
}

.week-width {
  width: 13%;
  height: 80px;
  box-sizing: border-box;
  padding: 10px 20px;
}

.noon-width {
  width: 91%;
  box-sizing: border-box;
}

.noon-height {
  height: 40px;
  line-height: 40px;
  box-sizing: border-box;
}

.bg-row {
  background: #191d4a;
}

.is_chick {
  background: rgba(13, 184, 149, 0.14);
}

.scheduling-selected {
  position: absolute;
  top: 10px;
  right: 10px;
}</style>

